package org.aspect.aspect;

import org.aspect.annotation.Permissions;
import org.aspect.interfaces.Authority;
import org.aspect.service.CheckPermissions;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * 用户权限标注
 *
 * @author LiKun
 * @date 2021/8/20 13:19
 */
@Aspect
@Component
public class PermissionsAspect {
    private static final String INSUFFICIENT_USER_RIGHTS = "用户权限不足";

    @Resource
    private CheckPermissions checkPermissions;

    @Around("@annotation(org.aspect.annotation.Permissions)")
    public Object execute(ProceedingJoinPoint joinPoint) throws Throwable {
        // 被 AOP 拦截的方法类
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Permissions permissions = signature.getMethod().getAnnotation(Permissions.class);

        Authority authority = (Authority) joinPoint.getArgs()[permissions.index()];
        if (checkPermissions.check(authority, permissions.authority())) {
            return joinPoint.proceed();
        } else {
            throw new Exception(INSUFFICIENT_USER_RIGHTS);
        }
    }
}
